package ruifight.member.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.core.util.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import ruifight.member.model.ShopAccount;
import ruifight.member.model.ShopAccountExample;
import ruifight.member.model.ShopInfo;
import ruifight.member.model.ShopInfoExample;
import ruifight.member.model.ShopInfoWithBLOBs;
import ruifight.member.model.UserInfo;
import ruifight.member.model.security.MyUserDetail;
import ruifight.member.service.AccountRecordService;
import ruifight.member.service.ShopAccountService;
import ruifight.member.service.ShopInfoService;
import ruifight.member.service.UserInfoService;
import ruifight.member.util.CommonUtil;


@Controller
@RequestMapping("/interface")
public class ShopInfoController {

	private static final Logger logger = LoggerFactory.getLogger(ShopInfoController.class);

	@Autowired
	public ShopInfoService shopInfoService;
	@Autowired
	public ShopAccountService shopAccountService;
	@Autowired
	public UserInfoService userInfoService;
	@Autowired
	public AccountRecordService accountRecordService;
	/**
	 * 获取商户信息列表
	 * @return
	 */
	@RequestMapping("/getShopInfoList")
	@ResponseBody
	public Map<String, Object> getShopInfoList(@RequestBody Map<String, Object> paramMap) {
		Map<String, Object> map = new HashMap<String, Object>();
		String cur_page= paramMap.get("cur_page").toString();
		String page_size= paramMap.get("page_size").toString();
		PageInfo<Map<String, Object>> pageInfo = shopInfoService.getShopInfoList(Integer.parseInt(cur_page), Integer.parseInt(page_size), paramMap);
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		return map;
	}

	/**     
	* 方法描述：   获取商户信息
	* @param shopInfoId
	* @return 
	* 创建人：浅缘0419   
	* 创建时间：2019年1月24日 下午4:00:01              
	*/
	@RequestMapping("/getShopInfoById")
	@ResponseBody
	public Map<String,Object> getShopInfoById(@RequestBody Map<String, Object> paramMap){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			ShopInfoWithBLOBs selectByPrimaryKey = shopInfoService.selectByPrimaryKey(Long.parseLong(paramMap.get("shopInfoId").toString()));
			ShopAccount selectByPrimaryKey2 = shopAccountService.selectByPrimaryKey(Long.parseLong(paramMap.get("shopAccountId").toString()));
			UserInfo selectByPrimaryKey3 = userInfoService.selectByPrimaryKey(selectByPrimaryKey.getUserInfoId());
			map.put("shopInfo", selectByPrimaryKey);
			map.put("shopAccount", selectByPrimaryKey2);
			map.put("userInfo", selectByPrimaryKey3);
		}catch (Exception e){
			map.put("shopInfo", "");
			map.put("shopAccount", "");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 添加商户
	 * @param shopInfo
	 * @return
	 */
	@RequestMapping("/addShopInfo")
	@ResponseBody
	public Map<String, Object> addShopInfo(@RequestBody Map<String, Object> paramMap){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = shopInfoService.addShopInfo(paramMap);
		}catch (Exception e){
			map.put("state", -1);
			map.put("msg", "系统崩溃了,请稍后再尝试~");
			e.printStackTrace();
		}
		return map;
	}

	/**
     * 修改商户信息
	 * @param shopInfo
     * @return
     */
	@RequestMapping("/updateShopInfo")
	@ResponseBody
	public Map<String, Object> updateInfoMember(@RequestBody Map<String, Object> paramMap){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = shopInfoService.updShopInfo(paramMap);
		}catch (Exception e){
			map.put("state",0);
			map.put("msg","修改失败");
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 删除商户
	 * @param shopInfo
	 * @return
	 */
	@RequestMapping("/delShopInfo")
	@ResponseBody
	public Map<String, Object> delShopInfo(@RequestBody Map<String, Object> paramMap){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = shopInfoService.delShopInfo(Long.parseLong(paramMap.get("shopInfoId").toString()));
		}catch (Exception e){
			map.put("state",0);
			map.put("msg","删除失败~");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 获取店铺名称及标签查询
	 * @param shopInfo
	 * @return
	 */
	@RequestMapping("/getSelectShopNameAndTitle")
	@ResponseBody
	public Map<String, Object> getSelectShopNameAndTitle(@RequestBody Map<String, Object> paramMap){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = shopInfoService.getSelectShopNameAndTitle(paramMap);
		}catch (Exception e){
			map.put("state",0);
			map.put("msg","获取店铺名称及标签失败~");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 通过店铺代码查询店铺及店铺账户信息
	 * @return
	 */
	@RequestMapping("/getShopAndShopAccountByShopCode/{shopCode}")
	@ResponseBody
	public Map<String, Object> getShopAndShopAccountByShopCode(@PathVariable String shopCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		ShopInfoExample shopInfoExample=new ShopInfoExample();
		shopInfoExample.createCriteria()
			.andShopCodeEqualTo(shopCode)
			.andShopStateEqualTo(1);
		ShopInfo shopInfo=shopInfoService.selectOneByExample(shopInfoExample);
		map.put("shopInfo", shopInfo);
		ShopAccountExample shopAccountExample=new ShopAccountExample();
		shopAccountExample.createCriteria()
			.andShopInfoIdEqualTo(shopInfo.getShopInfoId());
		ShopAccount shopAccount=shopAccountService.selectOneByExample(shopAccountExample);
		map.put("shopAccount", shopAccount);
		return map;
	}
	
	/**
	 * 通过店铺代码查询店铺信息
	 * @return
	 */
	@RequestMapping("/getShopByShopCode/{shopCode}")
	@ResponseBody
	public Map<String, Object> getShopByShopCode(@PathVariable String shopCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		ShopInfoExample shopInfoExample=new ShopInfoExample();
		shopInfoExample.createCriteria()
			.andShopCodeEqualTo(shopCode)
			.andShopStateEqualTo(1);
		ShopInfo shopInfo=shopInfoService.selectOneByExample(shopInfoExample);
		map.put("shopInfo", shopInfo);
		return map;
	}
	/**
	 * 获取图片信息
	 * @return
	 */
	@RequestMapping("/getShopPhoto")
	public void getShopPhoto(String photoPath,HttpServletResponse response) {
//		@RequestBody Map<String, Object> paramMap,HttpServletResponse response
//		String photoPath = paramMap.get("photoPath").toString();
		response.setContentType("image/jpg");
		OutputStream os =null;
		InputStream is =null;
		try {
			response.setContentType("image/jpg");
			os=response.getOutputStream();
			File file=new File(CommonUtil.getPropertiesParam("photoPath")+"/"+photoPath);
			is=new FileInputStream(file);
			byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
		} catch (Exception e) {
			logger.error("获取图片信息失败",e);
		}finally {
			try {
				os.close();
			} catch (IOException e) {
				os=null;
			} 
			try {
				is.close();
			} catch (IOException e) {
				is=null;
			} 
		}
	}
	/**     
	* 方法描述：   删除照片
	* @param photoPath
	* @return 
	* 创建人：浅缘0419   
	* 创建时间：2019年1月24日 下午3:56:02              
	*/
	@RequestMapping("/delPhoto")
	@ResponseBody
	public Map<String,Object> delPhoto(@RequestBody Map<String, Object> paramMap){
		String photoPath = paramMap.get("photoPath").toString();
		String shopInfoId = paramMap.get("shopInfoId").toString();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(shopInfoId!=null&&shopInfoId!="") {
				ShopInfoWithBLOBs info = shopInfoService.selectByPrimaryKey(Long.parseLong(shopInfoId));
				if(info.getBusinessPermitPhoto().equals(photoPath)) {
					info.setBusinessPermitPhoto("");
				}
				shopInfoService.updateByPrimaryKeySelective(info);
			}
			File file=new File(CommonUtil.getPropertiesParam("photoPath")+"/"+photoPath);
            if (file.exists()) {  
                if(file.delete()) {
                	map.put("state",1);
        			map.put("msg","删除照片成功~");
                }else {
                	map.put("state",0);
        			map.put("msg","删除照片失败~");
                }
            }else {
            	map.put("state",0);
    			map.put("msg","照片不存在~");
            }  
		}catch(Exception e) {
			e.printStackTrace();
			map.put("state",0);
			map.put("msg","系统崩溃,请稍后再尝试~");
		}
		return map;
	}
	
	/**     
	* 方法描述：   用于删除店铺照片
	* @param paramMap
	* @return 
	* 创建人：浅缘0419   
	* 创建时间：2019年1月25日 下午3:37:37              
	*/
	@RequestMapping("/delPhotoAttr2")
	@ResponseBody
	public Map<String,Object> delPhotoAttr2(@RequestBody Map<String, Object> paramMap){
		String photoPath = paramMap.get("photoPath").toString();
		String shopInfoId = paramMap.get("shopInfoId").toString();
		String attr2 = paramMap.get("attr2").toString();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(shopInfoId!=null&&shopInfoId!="") {
				ShopInfoWithBLOBs info = shopInfoService.selectByPrimaryKey(Long.parseLong(shopInfoId));
				info.setAttr2(attr2);
				shopInfoService.updateByPrimaryKeySelective(info);
			}
			File file=new File(CommonUtil.getPropertiesParam("photoPath")+"/"+photoPath);
            if (file.exists()) {  
                if(file.delete()) {
                	map.put("state",1);
        			map.put("msg","删除照片成功~");
                }else {
                	map.put("state",0);
        			map.put("msg","删除照片失败~");
                }
            }else {
            	map.put("state",0);
    			map.put("msg","照片不存在~");
            }  
		}catch(Exception e) {
			e.printStackTrace();
			map.put("state",0);
			map.put("msg","系统崩溃,请稍后再尝试~");
		}
		return map;
	}
	
	
	/**
	 * 通过店铺分页信息
	 * @return
	 */
	@RequestMapping("/getShopPage")
	@ResponseBody
	public Map<String, Object> getShopPage(@RequestBody Map<String, Object> paramMap) {
		Map<String, Object> map = new HashMap<String, Object>();
		String cur_page= paramMap.get("cur_page").toString();
		String page_size= paramMap.get("page_size").toString();
		PageInfo<Map<String, Object>> pageInfo = shopInfoService.getShopPage(Integer.parseInt(cur_page), Integer.parseInt(page_size), paramMap);
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		return map;
	}
	
	/**     
	* 方法描述：   店铺充值
	* @param paramMap
	* @return 
	* 创建人：浅缘0419   
	* 创建时间：2019年1月23日 下午7:18:11              
	*/
	@RequestMapping("/addShopOfMoney")
	@ResponseBody
	public Map<String, Object> addShopOfMoney(@RequestBody Map<String, Object> paramMap) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			shopInfoService.addShopOfMoney(paramMap);
			map.put("state",1);
			map.put("msg","充值成功~");
		}catch(Exception e) {
			map.put("state",0);
			map.put("msg","充值失败~");
			e.printStackTrace();
		}
		return map;
	}
	
	/**     
	* 方法描述：   店铺结算
	* @param paramMap
	* @return 
	* 创建人：浅缘0419   
	* 创建时间：2019年1月27日 下午6:01:22              
	*/
	@RequestMapping("/settlementShopMoney")
	@ResponseBody
	public Map<String, Object> settlementShopMoney(@RequestBody Map<String, Object> paramMap) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			shopInfoService.settlementShopMoney(paramMap);;
			map.put("state",1);
			map.put("msg","结算成功~");
		}catch(Exception e) {
			map.put("state",0);
			map.put("msg","结算失败~");
			e.printStackTrace();
		}
		return map;
	}
	@RequestMapping("/getCumulativeMoney")
	@ResponseBody
	public Map<String, Object> getCumulativeMoney(){
		Map<String, Object> map = new HashMap<String, Object>();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>(); 
			paramMap.put("payeeShopId", ud.getShopInfoId());
			Float cumulativeMoney=accountRecordService.getCumulativeMoney(paramMap);;
			map.put("state",1);
			map.put("cumulativeMoney",cumulativeMoney);
		}catch(Exception e) {
			map.put("state",0);
			map.put("cumulativeMoney",0);
			e.printStackTrace();
		}
		return map;
	}
	/**     
	* 方法描述：   获取个人商户信息
	* @param shopInfoId
	* @return 
	* 创建人：浅缘0419   
	* 创建时间：2019年1月24日 下午4:00:01              
	*/
	@RequestMapping("/getMyShopInfo")
	@ResponseBody
	public ShopInfoWithBLOBs getMyShopInfo(){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		ShopInfoWithBLOBs selectByPrimaryKey = null;
		try {
			selectByPrimaryKey = shopInfoService.selectByPrimaryKey(ud.getShopInfoId());
		}catch (Exception e){
			e.printStackTrace();
		}
		return selectByPrimaryKey;
	}
}
